import django_filters
from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, status
from rest_framework.filters import SearchFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from user.models import user, book, login
from user.ser import bookserializer, userserializer


# Create your views here.
class Page(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    page_query_param = 'page'


class userviews(django_filters.FilterSet):
    id = django_filters.NumberFilter(field_name='id', lookup_expr='exact')
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    age = django_filters.NumberFilter(field_name='age', lookup_expr='exact')
    class Meta:
        model = user
        fields = ['status','type_id']




class bookser(viewsets.ModelViewSet):
    queryset = book.objects.all()
    serializer_class = bookserializer


class userser(viewsets.ModelViewSet):
    queryset = user.objects.all()
    serializer_class = userserializer
    pagination_class = Page
    filter_backends = [DjangoFilterBackend,SearchFilter]
    filterset_class = userviews



class loginviews(APIView):
    def post(self, request):
        # 接收前端发送过来的用户名与密码
        username = request.data.get('username')
        password = request.data.get('password')

        try:
            # 从数据库查询当前登录的这个用户数据
            login1 = login.objects.get(username=username)
            # 判断密码是否易主
            if login1.password == password:
                # 设置登录时间
                # 定义返回的数据
                data = {
                    'id': login1.id,
                    'username': login1.username,
                }
                # 返回响应数据
                return Response({'code': 200, 'data': data, 'msg': '登录成功'})

        except login.DoesNotExist:
            pass

        return Response({'error': '用户名或密码错误'}, status=status.HTTP_400_BAD_REQUEST)
